var gulp = require('gulp');
var server = require('gulp-devserver');
var concat = require('gulp-concat');
var copy = require('gulp-file-copy');
var imagemin = require('gulp-imagemin');
var webpack = require("webpack");
var webpackConfig = require("./webpack.config.js");

gulp.task('devserver', function () {
  gulp.src('./dest')
    .pipe(server({
	  port: 33333,
      livereload: {
		clientConsole: true 
	  },
	  open: false,
	  debug: true,
      proxy: {
      	enable: true,
      	host: 'http://172.16.10.25:33334',
      	urls: [
			/^\/api/
		] 
      }
     }));
});

gulp.task("webpack", function(callback) {
	var config = Object.create(webpackConfig);
	// run webpack
	webpack(config,function(err, stats) {
		callback && callback();
	});
});

gulp.task('dest-css',function(){
	return gulp.src('./src/css/**/*.css')
		.pipe(concat('style.css'))
		.pipe(gulp.dest('./dest/css'));
});

gulp.task('dest-views',function(){
	return gulp.src('./src/views/**/*.html')
		.pipe(gulp.dest('./dest/views'));
});

gulp.task('dest-images',function(){
	return gulp.src('./src/images/**/*')
		.pipe(imagemin())
		.pipe(gulp.dest('./dest/images'));
});

gulp.task('dest-index',function(){
	return gulp.src('./src/index.html')
		.pipe(gulp.dest('./dest'));
});

gulp.task('dest-lib',function(){
	return gulp.src('./src/lib/**/*')
		.pipe(gulp.dest('./dest/lib'));
});

gulp.task('dest-app',function(){
	return gulp.src('./src/dist_js/app.js')
		.pipe(gulp.dest('./dest/js'));
})

gulp.task('server',['devserver'],function(){
	// watch for changes
	gulp.watch(['./src/js/**/*.js','./src/js/**/*.css','./src/js/**/*.html'], ['webpack']);
	gulp.watch('./src/dist_js/**/*.js', ['dest-app']);
	gulp.watch('./src/css/**/*.css',['dest-css']);
	gulp.watch('./src/views/**/*.html',  ['dest-views']);
	gulp.watch('./src/images/**/*',  ['dest-images']);
	gulp.watch('./src/index.html',['dest-index']);
	gulp.watch('./src/lib',['dest-lib']);
});	

gulp.task('dest',['webpack','dest-css','dest-views','dest-images','dest-index','dest-lib','dest-app','devserver']);


